package com.focusai.efairy.model.file;

import android.os.Handler;
import android.os.Message;

import com.focusai.efairy.model.request.DownloadFileRequest;
import com.focusai.efairy.network.HttpManager;

/**
 * Created by kingdee on 2016/7/23.
 */
public class FilePreviewModel implements DownloadFileRequest.IDownlaodCallback {
    public interface IPreviewCallback {
        void onFileDetailGet(FileInfo fileDetail);

        void onBeforeDownFile();

        void onDownLoadFileSuccess();

        void onDownLoadFileFailed();

        void onDownLoadFileProcess(int percent);
    }

    private final class MSGCODE {
        private final static int ON_DOWNLOAD_SUCCESS = 1;
        private final static int ON_DOWNLOAD_FAILED = 2;
        private final static int ON_DOWNLOAD_PROCESS = 3;
        private final static String PROCESS_KEY = "PROCESS_KEY";
    }

    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSGCODE.ON_DOWNLOAD_FAILED:
                    mCallack.onDownLoadFileFailed();
                    break;
                case MSGCODE.ON_DOWNLOAD_SUCCESS:
                    mCallack.onDownLoadFileSuccess();
                    break;
                case MSGCODE.ON_DOWNLOAD_PROCESS:
                    mCallack.onDownLoadFileProcess((Integer) msg.obj);
                    break;
                default:
                    break;

            }
        }
    };

    public FilePreviewModel(IPreviewCallback callback) {
        mCallack = callback;
    }

    private IPreviewCallback mCallack;

    private DownloadFileRequest mDownloadRequest;

    public void downLoadFile(final FileInfo fileInfos) {
        mCallack.onBeforeDownFile();
        mDownloadRequest = new DownloadFileRequest(fileInfos, this);
        HttpManager.getInstance().sendRequest(mDownloadRequest);
    }

    public void pauseDownLoad() {
        if (null != mDownloadRequest) {
            mDownloadRequest.pauseDownLoad();
        }
    }

    public void resumeDownload() {
        if (null != mDownloadRequest) {
            mDownloadRequest.resumeDownload();
        }
    }

    public void stopDownload() {
        if (null != mDownloadRequest) {
            mDownloadRequest.stopDownload();
        }
    }

    @Override
    public void onDownLoadFileSuccess() {
        Message msg = mHander.obtainMessage();
        msg.what = MSGCODE.ON_DOWNLOAD_SUCCESS;
        mHander.sendMessage(msg);
    }

    @Override
    public void onDownLoadFileFailed() {
        Message msg = mHander.obtainMessage();
        msg.what = MSGCODE.ON_DOWNLOAD_FAILED;
        mHander.sendMessage(msg);
    }

    @Override
    public void onDownLoadFileProcess(int percent) {
        Message msg = mHander.obtainMessage();
        msg.what = MSGCODE.ON_DOWNLOAD_PROCESS;
        msg.obj = percent;
        mHander.sendMessage(msg);
    }
}
